package com.audaque.springboot.foshanupload.web.webdemo.controller;

import cn.hutool.core.io.resource.ResourceUtil;
import com.audaque.springboot.foshanupload.log.anno.WebLogAnno;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.net.URI;
import java.net.URL;

@Slf4j
@RestController
@RequestMapping("scriptEngineManager")
public class ScriptEngineManagerController {

    @WebLogAnno
    @GetMapping("/test1")
    public void test1() throws Exception {
        // 创建一个脚本执行引擎管理器
        ScriptEngineManager factory = new ScriptEngineManager();
        // 创建一个JavaScript引擎
        ScriptEngine engine = factory.getEngineByName("nashorn");
        // 执行JavaScript代码
        engine.eval("print('Hello, World')");
    }

    /**
     * 根据指定的JS文件执行JavaScript代码
     */

    @WebLogAnno
    @GetMapping("/test2")
    public void test2() throws Exception {
        // 创建一个脚本执行引擎管理器
        ScriptEngineManager factory = new ScriptEngineManager();
        // 创建一个JavaScript引擎
        ScriptEngine engine = factory.getEngineByName("nashorn");
        // 根据指定的JS文件执行JavaScript代码
        URL url = ResourceUtil.getResource("js/test2.js");
        URI uri = url.toURI();
        engine.eval(new java.io.FileReader(new File(uri)));
    }

    /**
     * 脚本变量
     */
    @WebLogAnno
    @GetMapping("/test3")
    public void test3() throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");
        URL url = ResourceUtil.getResource("txt/test.txt");
        URI uri = url.toURI();
        File f = new File(uri);
        // 将File对象作为变量公开给脚本
        engine.put("f", f);
        // 执行JAVA传入的对象方法以及脚本方法
        engine.eval("print(f.getAbsolutePath())");
    }



}

